//
//  XMString+Extension.swift
//  AnneKit-Swift
//
//  Created by 寜小陌 on 2021/3/3.
//  Copyright © 2021 宁小陌. All rights reserved.
//

import Foundation
import UIKit
import CommonCrypto

//MARK: 类型转换
extension String {
    
    /// 字符串 转 Int
    public var nxm_intValue: Int {
        let str = self
        return Int(str) ?? 0
    }
    
    /// 字符串 转 Float
    public var nxm_floatValue: Float {
        let str = self
        return Float(str) ?? 0
    }
    
    /// 字符串 转 Double
    public var nxm_doubleValue: Double {
        let str = self
        return Double(str) ?? 0
    }
    
    /// 字符串 转 Number
    public var nxm_numberValue: NSNumber {
        let str = self
        let value = Int(str) ?? 0
        return NSNumber.init(value: value)
    }
    
    /// 字符串转数组
    var nxm_toArray:[String]{
        return self.compactMap({String($0)})
    }
}

extension String {
    
    /// 获取不为options字符串
    static func nxm_getString(_ string:String?) -> String {
        return String.nxm_isStringNil(string) ? "" : string!
    }
    
    /// 判断字符串是否为空（true为nil false不为nil）
    static func nxm_isStringNil(_ string:String?) -> Bool {
        guard let string = string else { return true }
        return string.count == 0 ? true : false
    }
    ///是否是邮箱
    public var nxm_isEmail: Bool {
        let regular = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
        return range(of: regular, options: .regularExpression, range: nil, locale: nil) != nil
    }
    
    /// 是否是手机号
    public var nxm_isMobile: Bool {
        guard !self.isEmpty else{
            return false
        }
        let phoneRegix = "[123456789][0-9]{8}([0-9]{1})?"
        let phoneTest = NSPredicate(format: "SELF MATCHES %@", phoneRegix)
        return phoneTest.evaluate(with: self)
    }
    
    /// 是否包含表情
    var nxm_isIncludesEmoji:Bool{
        for i in 0...count {
            let c: unichar = (self as NSString).character(at: i)
            if (0xD800 <= c && c <= 0xDBFF) || (0xDC00 <= c && c <= 0xDFFF) {
                return true
            }
        }
        return false
    }
    
    /// 判断是否电话号码 11位并且首位是1
    public func nxm_isPhoneNumber() -> Bool {
        if self.count != 11 { return false }
        if self.first != "1" { return false }
        return true
    }
    
    /// 是否是字母数字的组合
    var nxm_isAlphanumeric: Bool {
        let regular = "[^a-zA-Z0-9]"
        return !isEmpty && range(of: regular, options: .regularExpression) == nil
    }

    /// 校验密码强度,必须包含字母和数字，长度必须大于等于6
    public func nxm_isPassword() -> Bool {
        if self.count <= 5 {
            return false
        }
        let numberRegex:NSPredicate = NSPredicate(format:"SELF MATCHES %@","^.*[0-9]+.*$")
        let letterRegex:NSPredicate = NSPredicate(format:"SELF MATCHES %@","^.*[A-Za-z]+.*$")
        if numberRegex.evaluate(with: self) && letterRegex.evaluate(with: self) {
            return true
        } else {
            return false
        }
    }
    /// URL编码
    public var nxm_urlEncoded: String {
        let characterSet = CharacterSet(charactersIn: ":/?#[]@!$ &'()*+,;=\"<>%{}|\\^~`")
        return self.addingPercentEncoding(withAllowedCharacters: characterSet)!
    }
    /// URL解码
    public var nxm_urlDecode: String? {
        return self.removingPercentEncoding
    }
    
    /// 是否是URL
    public var nxm_isValidUrl: Bool {
        return URL(string: self) != nil
    }
    
    /// base64编码
    var nxm_base64: String {
        let plainData = (self as NSString).data(using: String.Encoding.utf8.rawValue)
        let base64String = plainData!.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
        return base64String
    }
    
    /// Base64解码
    public var nxm_base64Decode: String? {
        if let data = Data(base64Encoded: self) {
            return String(data: data, encoding: .utf8)
        }
        return nil
    }
}

extension String {
    
    /// 计算字符串的高度
    public func nxm_getHeight(font: CGFloat, width: CGFloat) -> CGFloat {
        return nxm_getHeight(font: UIFont.systemFont(ofSize: font), width: width)
    }
    
    public func nxm_getHeight(font: UIFont, width: CGFloat) -> CGFloat {
        let statusLabelText: NSString = self as NSString
        let size = CGSize.init(width: width, height: 9000)
        let dic = NSDictionary(object: font, forKey: NSAttributedString.Key.font as NSCopying)
        let strSize = statusLabelText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic as? [NSAttributedString.Key : Any], context: nil).size
        return strSize.height
    }
    
    /// 计算字符串的宽度
    public func nxm_getWidth(font: CGFloat, height: CGFloat) -> CGFloat {
        return nxm_getWidth(font: UIFont.systemFont(ofSize: font), height: height)
    }
    public func nxm_getWidth(font:UIFont,height:CGFloat) -> CGFloat {
        let statusLabelText: NSString = self as NSString
        let size = CGSize.init(width: 9999, height: height)
        let dic = NSDictionary(object: font, forKey: NSAttributedString.Key.font as NSCopying)
        let strSize = statusLabelText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic as? [NSAttributedString.Key : Any], context: nil).size
        return strSize.width
    }
    
    /// 截取指定区间的字符串
    public func nxm_clipSubString(range: (location: Int, length: Int)) -> String {
        
        if range.location + range.length >= self.count {
            return self
        }
        let locationIndex = self.index(startIndex, offsetBy: range.location)
        let range = locationIndex..<self.index(locationIndex, offsetBy: range.length)
        return String(self[range])
    }
    
    /// 字符串的截取 从头截取到指定index
    public func nxm_clipFromPrefix(to index: Int) -> String {
        if self.count <= index {
            return self
        } else {
            let index = self.index(self.startIndex, offsetBy: index)
            let str = self.prefix(upTo: index)
            return String(str)
        }
    }
    
    /// 字符串的截取 从指定位置截取到尾部
    public func nxm_cutToSuffix(from index: Int) -> String {
        if self.count <= index {
            return self
        } else {
            let selfIndex = self.index(self.startIndex, offsetBy: index)
            let str = self.suffix(from: selfIndex)
            return String(str)
        }
    }
    
    ///替换指定范围内的字符串
    mutating func nxm_stringByReplacingCharactersInRange(index:Int,length:Int,replacText:String) -> String {
        let startIndex = self.index(self.startIndex, offsetBy: index)
        self.replaceSubrange(startIndex..<self.index(startIndex, offsetBy: length), with: replacText)
        return self
    }
    /// 替换指定字符串
    mutating func nxm_stringByReplacingstringByReplacingString(text:String,replacText:String) -> String {
        return self.replacingOccurrences(of: text, with: replacText)
    }
  
    /// 删除最后一个字符
    mutating func nxm_deleteEndCharacters() -> String {
        self.remove(at: self.index(before: self.endIndex))
        return self
    }
    /// 删除指定字符串
    mutating func nxm_deleteString(string:String) -> String {
        return self.replacingOccurrences(of: string, with: "")
    }
    
    /// 字符的插入
    mutating func nxm_insertString(text:Character,index:Int) -> String{
        let start = self.index(self.startIndex, offsetBy: index)
        self.insert(text, at: start)
        return self
    }
    /// 字符串的插入
    mutating func nxm_insertString(text:String,index:Int) -> String{
        let start = self.index(self.startIndex, offsetBy: index)
        self.insert(contentsOf: text, at: start)
        return self
    }
    
    /// 将字符串通过指定的字符串拆分为字符串数组
    public func nxm_split(string:String) -> [String] {
        return NSString(string: self).components(separatedBy: string)
    }
    
    /// 去空格
    public func nxm_removeAllSapce() -> String{
        return self.replacingOccurrences(of: " ", with: "", options: .literal, range: nil)
    }

    ///获取某个字符串在总字符串的位置
    public func nxm_positionOf(sub:String, backwards:Bool = false)->Int {
        var pos = -1
        if let range = range(of:sub, options: backwards ? .backwards : .literal ) {
            if !range.isEmpty {
                pos = self.distance(from:startIndex, to:range.lowerBound)
            }
        }
        return pos
    }
}

extension String {
    
    /// 设置文本的颜色
    public func nxm_setMutableColor(_ color: UIColor,range: NSRange) -> NSAttributedString {
        let attributedString = NSMutableAttributedString.init(string: self)
        attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
        return attributedString
    }
    
    /// 设置文本的字体大小
    public func nxm_setMutableFont(_ font: CGFloat, range: NSRange) -> NSAttributedString {
        let attributedString = NSMutableAttributedString.init(string: self)
        attributedString.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: font), range: range)
        return attributedString
    }
    
    /// 设置文本的字体大小和颜色
    public func nxm_setMutableFontAndColor(font: CGFloat, fontRange: NSRange, color: UIColor, colorRange: NSRange) -> NSAttributedString {
            let attributedString = NSMutableAttributedString.init(string: self)
            attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: colorRange)
            
            attributedString.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: font), range: fontRange)
            return attributedString
    }
    
    /// 设置删除线 NSStrikethroughStyleAttributeName
    public func nxm_setDeleteLine() -> NSAttributedString {
        let range = NSMakeRange(0, self.count)
        let attributedString = NSMutableAttributedString.init(string: self)
        attributedString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 1, range: range)
        return attributedString
    }
    
    /// 同时设置设置删除线和字体大小
    public func nxm_setMutableFontAndDeleteLine(_ font: CGFloat,range: NSRange) -> NSAttributedString {
        let attributedString = NSMutableAttributedString.init(string: self)
        attributedString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 1, range: range)
        
        let deleTeRange = NSMakeRange(0, self.count)
        attributedString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 1, range: deleTeRange)
        
        return attributedString
    }
    
    /// 设置文本的行间距
    public func nxm_setLineSpace(lineSpace: CGFloat) -> NSAttributedString {
        let attributedString = NSMutableAttributedString.init(string: self)
        let paragraphStyle = NSMutableParagraphStyle.init()
        paragraphStyle.lineSpacing = lineSpace
        let range = NSRange.init(location: 0, length: self.count)
        attributedString.addAttributes([NSAttributedString.Key.paragraphStyle:paragraphStyle], range: range)
        
        return attributedString
    }
    
    /// 设置图文详情
    public func nxm_setTextAttachment(image: UIImage, imageFrame: CGRect) -> NSMutableAttributedString {
        
        let attributedStrM : NSMutableAttributedString = NSMutableAttributedString()
        let nameStr : NSAttributedString = NSAttributedString(string: " " + self, attributes: nil)
        
        let attachment = NSTextAttachment.init()
        attachment.image = image
        attachment.bounds = imageFrame
        
        attributedStrM.append(NSAttributedString(attachment: attachment))
        attributedStrM.append(nameStr)
        return attributedStrM
    }
}
